from tkinter import *
from tkinter import ttk
from tkinter.messagebox import *
import requests
import os



directory = (os.path.split(os.path.realpath(__file__))[0]).split("\\")
directory = "/".join(directory)+"/"

def get_window_positon(width,height):
    return ((window.winfo_screenwidth() - width) // 2),((window.winfo_screenheight() - height)//2)

def window_size(window,width,height):
    window.minsize(width,height)
    window.resizable(0,0)
    pos = get_window_positon(width,height)
    window.geometry(f'{width}x{height}+{pos[0]}+{pos[1]}')

def translate(_from,to,text):
    languageDict = {'自动检测':0,'中文':1,'英文':2,'日文':3,'韩文':4,'法文':5,'西班牙文':6,'葡萄牙文':7,'德文':8,'意大利文':9,'俄文':10}
    data = {
        "text":text,
        "from":languageDict[_from],
        "to":languageDict[to]
    }
    try:
        r = requests.post('https://www.yuanfudao.com/ada-student-app-api/api/translate',data=data).json()
        if r['code'] != 0:
            showerror('Error',r['msg'])
            return r['msg']
        return r["result"]
    except:
        showerror('Error','翻译失败')
        return "翻译失败"


if __name__ == "__main__":
    window = Tk()
    window.title('翻译小程序')
    window.iconphoto(False,PhotoImage(file=f'{directory}img/翻译.png'))
    window_size(window,450,400)
    var_from = StringVar()
    com_from = ttk.Combobox(window, textvariable=var_from,width=10)
    com_from.place(x=110,y=50)
    com_from["value"] = ['自动检测','中文','英文','日文','韩文','法文','西班牙文','葡萄牙文','德文','意大利文','俄文']
    com_from.current(0)
    lab = Label(window,text="»",font=("宋体",25)).place(x=210,y=40)
    var_to = StringVar()
    com_to = ttk.Combobox(window, textvariable=var_to,width=10)
    com_to.place(x=240,y=50)
    com_to["value"] = ['中文','英文','日文','韩文','法文','西班牙文','葡萄牙文','德文','意大利文','俄文']
    com_to.current(0)
    f_text = Text(window,width=35,height=7)
    f_text.place(x=100,y=100)
    c_text = Text(window,width=35,height=7,state=DISABLED)
    c_text.place(x=100,y=250)
    def btn_r():
        _from = var_from.get()
        to = var_to.get()
        text = f_text.get(1.0,'end')
        translate_text = translate(_from,to,str(text))
        c_text.config(state=NORMAL)
        c_text.delete('1.0','end')
        c_text.insert("insert",str(translate_text))
        c_text.config(state=DISABLED)
    Button(window,text='翻译',command=btn_r).place(x=200,y=205)
    window.mainloop()